import configparser
import os
import random
import re
import sys
import time
import webbrowser

import mutagen.id3
import requests
from PyQt5 import QtWidgets
from PyQt5.QtCore import QCoreApplication, Qt, QUrl, QTimer
from PyQt5.QtGui import QPixmap, QFontDatabase
from PyQt5 import QtCore
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtWidgets import QListWidgetItem
from mutagen.flac import FLAC
from mutagen.wave import WAVE
from mutagen.dsf import DSF
from mutagen.dsdiff import DSDIFF

import OnlineInfo
from mainwindow import Ui_MainWindow
from sqlite_lib import UsingSqlite

now_version = 'v1.1.2'


def readSongInfo(path, is_creat_cover):
    """读取歌曲信息"""
    # 获取文件后缀
    filetype = os.path.splitext(path)[-1]
    title = '标题'
    artist = '作者'
    album = '专辑'
    date = '日期'
    genre = '风格'
    lyrics = '歌词'
    song_info = {title: '暂无', artist: '暂无', album: '暂无', date: '暂无', genre: '暂无', lyrics: '暂无'}
    # 清理封面
    if os.path.exists('cache/cover.png'):
        os.remove('cache/cover.png')

    if filetype == '.mp3' or filetype == '.wav' or filetype == '.dsf' or filetype == '.dff':
        if filetype == '.mp3':
            audio = mutagen.id3.ID3(path)
        elif filetype == '.wav':
            audio = WAVE(path)
        elif filetype == '.dsf':
            audio = DSF(path)
        else:
            audio = DSDIFF(path)
        # 封面
        if is_creat_cover:
            if not audio.get('APIC:') is None:
                artwork = audio.get('APIC:').data
                with open('cache/cover.png', 'wb') as img:
                    img.write(artwork)
        # 信息
        if not audio.get('TIT2') is None:
            song_info[title] = str(audio.get('TIT2'))
        if not audio.get('TPE1') is None:
            song_info[artist] = str(audio.get('TPE1'))
        if not audio.get('TALB') is None:
            song_info[album] = str(audio.get('TALB'))
        if not audio.get('TDRC') is None:
            song_info[date] = str(audio.get('TDRC'))
        if not audio.get('TCON') is None:
            song_info[genre] = str(audio.get('TCON'))
        if not audio.get('USLT::XXX') is None:
            song_info[lyrics] = str(audio.get('USLT::XXX'))
        elif os.path.exists(os.path.splitext(path)[0] + '.lrc'):
            with open(os.path.splitext(path)[0] + '.lrc', "r", encoding='utf-8', errors='ignore') as f:  # 打开文件
                song_info[lyrics] = f.read()  # 读取本地歌词

    elif filetype == '.flac':
        audio = FLAC(path)
        # 封面
        if is_creat_cover:
            if audio.pictures:
                artwork = audio.pictures[0].data
                with open('cache/cover.png', 'wb') as img:
                    img.write(artwork)
        # 信息
        if not audio.get('title') is None:
            song_info[title] = audio.get('title')[0]
        if not audio.get('artist') is None:
            song_info[artist] = audio.get('artist')[0]
        if not audio.get('album') is None:
            song_info[album] = audio.get('album')[0]
        if not audio.get('date') is None:
            song_info[date] = audio.get('date')[0]
        if not audio.get('genre') is None:
            song_info[genre] = audio.get('genre')[0]
        if not audio.get('lyrics') is None:
            song_info[lyrics] = audio.get('lyrics')[0]
        elif os.path.exists(os.path.splitext(path)[0] + '.lrc'):
            with open(os.path.splitext(path)[0] + '.lrc', "r", encoding='utf-8', errors='ignore') as f:  # 打开文件
                song_info[lyrics] = f.read()  # 读取本地歌词

    return song_info


def splitLrc(get_lyrics):
    """分割歌词，格式化为字典"""
    lrc_list = get_lyrics.splitlines()
    # 时间戳正则
    func = re.compile("\\[.*?]")  # 为符合PEP8规范，反斜杠双写，实际使用一个也可以
    # 根据时间戳，转换成字典
    lrc_dict = {}
    time_list = []
    for list_item in lrc_list:
        if func.search(list_item) is None:
            continue
        lrc_time = func.search(list_item).group()
        lrc_time_float_list = lrc_time[1:-1].split(":")
        if lrc_time_float_list[0].isdigit() is False:
            continue
        lrc_time_int = int(lrc_time_float_list[0]) * 60000 + int(float(lrc_time_float_list[1]) * 1000)
        lrc_text = func.sub('', list_item)
        lrc_text = ' '.join(lrc_text.split())
        if lrc_dict.get(lrc_time_int):
            lrc_dict[lrc_time_int].append(lrc_text)
        else:
            lrc_dict[lrc_time_int] = [lrc_text]
    for key in lrc_dict:
        time_list.append(key)
    return lrc_dict, time_list


def compareVersion(local, net):
    """比较版本号大小"""
    local, net = local[1:], net[1:]
    local_list = local.split('.')
    net_list = net.split('.')
    for num_local, num_net in zip(local_list, net_list):
        if num_local > num_net:
            return False
        elif num_local < num_net:
            return True
    return False


class MyWindow(QtWidgets.QMainWindow):
    """主窗体类"""

    def __init__(self):
        # 继承父类
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # 载入字体
        if os.path.exists("fonts/霞鹜文楷.ttf"):
            QFontDatabase.addApplicationFont("fonts/霞鹜文楷.ttf")

        # 窗口相关
        self.setWindowFlags(Qt.FramelessWindowHint)  # 设置为无标题栏
        self.setAttribute(Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.ui.pushButton_update.setText(now_version)  # 设定版本号

        # 控件阴影
        self.effect_shadow = QtWidgets.QGraphicsDropShadowEffect(self)  # 阴影效果
        self.effect_shadow.setOffset(0, 0)  # 偏移
        self.effect_shadow.setBlurRadius(10)  # 阴影半径
        self.effect_shadow.setColor(Qt.black)  # 阴影颜色
        self.ui.widget.setGraphicsEffect(self.effect_shadow)  # 将设置套用到widget窗口

        self.effect_shadow = QtWidgets.QGraphicsDropShadowEffect(self)  # 阴影效果
        self.effect_shadow.setOffset(0, 0)  # 偏移
        self.effect_shadow.setBlurRadius(10)  # 阴影半径
        self.effect_shadow.setColor(Qt.black)  # 阴影颜色
        self.ui.label_pic_under.setGraphicsEffect(self.effect_shadow)  # 将设置套用到label_pic

        # 拖动变量初始化
        self.move_drag = False
        self.move_DragPosition = 0

        # 按键绑定
        self.ui.pushButton_start.clicked.connect(self.song_start)
        self.ui.pushButton_path.clicked.connect(self.getPath)
        self.ui.pushButton_is_comment.clicked.connect(self.changeCommentMode)
        self.ui.listWidget.doubleClicked.connect(self.song_doubleClicked)
        self.ui.listWidget_2.doubleClicked.connect(self.lrc_doubleClicked)
        self.ui.listWidget_3.doubleClicked.connect(self.info_doubleClicked)
        self.ui.horizontalSlider.sliderReleased.connect(self.sliderRelease)
        self.ui.horizontalSlider.sliderPressed.connect(self.sliderPress)
        self.ui.horizontalSlider.sliderMoved.connect(self.sliderMove)
        self.ui.pushButton_red.clicked.connect(self.closeWindow)
        self.ui.pushButton_green.clicked.connect(self.showMinimized)
        # self.ui.pushButton_yellow.clicked.connect(self.showMaximized)  # 不使用最大化
        self.ui.pushButton_next.clicked.connect(self.startNext)
        self.ui.pushButton_goback.clicked.connect(self.song_goBack)
        self.ui.pushButton_random.clicked.connect(self.changePlayMode)
        self.ui.pushButton_is_online.clicked.connect(self.changeLrcMode)
        self.ui.lineEdit.textChanged.connect(self.searchSong)
        self.ui.pushButton_is_trans.clicked.connect(self.changeTransMode)
        self.ui.pushButton_update.clicked.connect(self.getUpdate)

        # 计时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.Timer1)

        # 初始化
        self.player = QMediaPlayer(flags=QMediaPlayer.Flags())  # 无参数也行，但是会有提示
        self.list_path = []
        self.file_num = 0
        self.directory_path = ''
        self.song_path = ''
        self.is_start = False
        self.is_sliderPress = False
        self.is_lrc_trans = True
        self.lrc_time_index = 0
        self.song_index = 0
        self.lrc_dict = {}
        self.lrc_time_list = []
        self.song_info = {}
        self.song_info_list = []
        self.play_mode = 0
        self.lrc_mode = 0
        self.comment_mode = 0
        self.is_get_comment = False

        self.ui.label_pic_hires.setVisible(False)  # 是否显示小金标
        self.ui.lineEdit.setClearButtonEnabled(True)  # 显示一个清空按钮
        self.ui.widget_comment.setVisible(False)  # 关闭评论列表

        # 创建缓存目录
        if not os.path.exists('cache'):
            os.makedirs('cache')

        # 列表自动换行
        # self.ui.listWidget.setWordWrap(True)
        self.ui.listWidget_2.setWordWrap(True)
        self.ui.listWidget_3.setWordWrap(True)
        self.ui.listWidget_comment.setWordWrap(True)

        # 列表滚动条步长
        self.ui.listWidget.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
        self.ui.listWidget.verticalScrollBar().setSingleStep(15)
        self.ui.listWidget_2.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
        self.ui.listWidget_2.verticalScrollBar().setSingleStep(15)
        self.ui.listWidget_comment.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
        self.ui.listWidget_comment.verticalScrollBar().setSingleStep(10)

        # 气泡提示
        self.ui.pushButton_red.setToolTip('关闭')
        self.ui.pushButton_yellow.setToolTip('最大化')
        self.ui.pushButton_green.setToolTip('最小化')
        self.ui.pushButton_next.setToolTip('下一首')
        self.ui.pushButton_path.setToolTip('选择路径')
        self.ui.pushButton_goback.setToolTip('回到当前播放位置')
        self.ui.pushButton_is_comment.setToolTip('切换评论显示')
        self.ui.pushButton_is_trans.setToolTip('切换翻译')
        self.ui.lineEdit.setPlaceholderText('搜索')

        # 创建线程
        self.thread1 = Thread()
        self.thread1.signal_item.connect(self.thread_search_num)
        self.thread1.signal_stop.connect(self.thread_search_stop)

        # 载入配置文件
        self.loadSetting()

    def closeWindow(self):
        """关闭按钮"""
        # 自动保存配置，不提示
        self.saveSetting(1)
        QCoreApplication.quit()

    def loadSetting(self):
        """载入配置文件"""
        if os.path.exists('setting.ini'):
            config = configparser.ConfigParser()
            config.read('setting.ini')

            # 载入播放路径，检测数目
            self.directory_path = config.get('PATH', 'directory_path')
            if self.directory_path:
                self.checkDB()

            # 载入数据库数据
            if os.path.exists('songs.db'):
                self.searchTableSelect('')

            # 载入播放模式
            self.play_mode = int(config.get('MainConfig', 'play_mode'))
            self.lrc_mode = int(config.get('MainConfig', 'lrc_mode'))
            self.setPlayModeStyleSheet()
            self.setLrcModeStyleSheet()

    def saveSetting(self, mode):
        """保存配置文件"""
        config = configparser.ConfigParser()
        config.add_section('PATH')
        config.set('PATH', 'directory_path', self.directory_path)
        config.add_section('MainConfig')
        config.set('MainConfig', 'play_mode', str(self.play_mode))
        config.set('MainConfig', 'lrc_mode', str(self.lrc_mode))
        config.write(open('setting.ini', 'w'))
        print('保存配置完成')
        if mode != 1:
            QtWidgets.QMessageBox.information(self, "保存配置", '保存完成！', QtWidgets.QMessageBox.Ok)

    def sliderMove(self):
        """移动滑条，刷新标签"""
        self.ui.label.setText(time.strftime('%M:%S', time.localtime(self.ui.horizontalSlider.value() / 1000)))

    def sliderRelease(self):
        """释放滑条，调整进度"""
        self.player.setPosition(self.ui.horizontalSlider.value())
        self.lrc_time_index = 0
        self.is_sliderPress = False

    def sliderPress(self):
        """按住滑条"""
        self.is_sliderPress = True

    def lrc_doubleClicked(self):
        """双击歌词，跳转对应时间"""
        # 已获取歌词时间戳
        if len(self.lrc_time_list) != 0:
            print(self.lrc_time_list[self.ui.listWidget_2.currentRow()])
            self.player.setPosition(self.lrc_time_list[self.ui.listWidget_2.currentRow()])
            self.lrc_time_index = 0

    def Timer1(self):
        """定时器，500ms"""
        # 时间标签格式化
        if not self.is_sliderPress:
            self.ui.label.setText(time.strftime('%M:%S', time.localtime(self.player.position() / 1000)))
            self.ui.label_2.setText(time.strftime('%M:%S', time.localtime(self.player.duration() / 1000)))
        # 歌词时间戳定位
        if len(self.lrc_time_list) != 0:
            while True:
                # 保证列表不超限
                if self.lrc_time_index > len(self.lrc_time_list) - 1:
                    break
                # 匹配歌词时间
                elif self.lrc_time_list[self.lrc_time_index] < self.player.position():
                    self.lrc_time_index += 1
                else:
                    break
                # 移动到对应位置并选中
                # self.ui.listWidget_2.verticalScrollBar().setSliderPosition(self.lrc_time_index - 1)
                self.ui.listWidget_2.setCurrentRow(self.lrc_time_index - 1)
                item = self.ui.listWidget_2.item(self.lrc_time_index - 1)
                self.ui.listWidget_2.scrollToItem(item, QtWidgets.QAbstractItemView.PositionAtCenter)

        # 设定滑条限度
        self.ui.horizontalSlider.setMaximum(self.player.duration())
        self.ui.horizontalSlider.setMinimum(0)
        # 释放滑条，调整进度
        if not self.is_sliderPress:
            self.ui.horizontalSlider.setValue(self.player.position())
        # 歌曲播放完毕
        if self.player.position() == self.player.duration():
            print('Time over')
            self.startNext()

    def changeCommentMode(self):
        """切换评论显示"""
        if self.song_path != '':
            self.comment_mode += 1
            if self.comment_mode > 1:
                self.comment_mode = 0
            if self.comment_mode == 1:
                self.ui.widget_comment.setVisible(True)
                self.ui.widget_info.setVisible(False)
                if self.is_get_comment is False:
                    self.song_getComment()
            else:
                self.ui.widget_comment.setVisible(False)
                self.ui.widget_info.setVisible(True)

    def changeTransMode(self):
        """切换翻译模式"""
        if self.song_path != '':
            self.is_lrc_trans = bool(1 - self.is_lrc_trans)
            self.song_init()

    def changeLrcMode(self):
        """切换歌词模式"""
        self.lrc_mode += 1
        if self.lrc_mode > 1:
            self.lrc_mode = 0
        self.setLrcModeStyleSheet()

    def setLrcModeStyleSheet(self):
        """歌词图标样式"""
        if self.lrc_mode == 0:
            self.ui.pushButton_is_online.setToolTip('内嵌歌词')
            self.ui.pushButton_is_online.setStyleSheet("QPushButton{\n"
                                                       "image: url(:/icon/images/cloud_off.png);\n}\n"
                                                       "QPushButton:hover{\n"
                                                       "image: url(:/icon/images/cloud_off 深色.png);\n}")
        if self.lrc_mode == 1:
            self.ui.pushButton_is_online.setToolTip('在线歌词')
            self.ui.pushButton_is_online.setStyleSheet("QPushButton{\n"
                                                       "image: url(:/icon/images/cloud_download.png);\n}\n"
                                                       "QPushButton:hover{\n"
                                                       "image: url(:/icon/images/cloud_download 深色.png);\n}")

    def changePlayMode(self):
        """切换播放模式"""
        self.play_mode += 1
        if self.play_mode > 2:
            self.play_mode = 0
        self.setPlayModeStyleSheet()

    def setPlayModeStyleSheet(self):
        """播放图标样式"""
        if self.play_mode == 0:
            self.ui.pushButton_random.setToolTip('列表循环')
            self.ui.pushButton_random.setStyleSheet("QPushButton{\n"
                                                    "image: url(:/icon/images/列表循环.png);\n}\n"
                                                    "QPushButton:hover{\n"
                                                    "image: url(:/icon/images/列表循环 深色.png);\n}")
        if self.play_mode == 1:
            self.ui.pushButton_random.setToolTip('单曲循环')
            self.ui.pushButton_random.setStyleSheet("QPushButton{\n"
                                                    "image: url(:/icon/images/单曲循环.png);\n}\n"
                                                    "QPushButton:hover{\n"
                                                    "image: url(:/icon/images/单曲循环 深色.png);\n}")
        if self.play_mode == 2:
            self.ui.pushButton_random.setToolTip('随机播放')
            self.ui.pushButton_random.setStyleSheet("QPushButton{\n"
                                                    "image: url(:/icon/images/随机播放.png);\n}\n"
                                                    "QPushButton:hover{\n"
                                                    "image: url(:/icon/images/随机播放 深色.png);\n}")

    def playOrder(self):
        """顺序播放"""
        self.song_index += 1
        if self.file_num - 1 < self.song_index:
            self.song_index = 0

    def playRandom(self):
        """随机播放"""
        while True:
            random_num = random.randint(0, self.file_num - 1)  # 伪随机数
            if random_num != self.song_index or self.file_num == 1:  # 避免随机到同一首
                break
        self.song_index = random_num

    def playOneOnly(self):
        """单曲循环"""
        pass  # 究极摸鱼函数

    def startNext(self):
        """下一首"""
        print('下一首')
        if self.file_num != 0:
            self.is_start = False
            # 播放顺序
            if self.play_mode == 0:  # 顺序
                self.playOrder()
            elif self.play_mode == 1:  # 单曲
                self.playOneOnly()
            elif self.play_mode == 2:  # 随机
                self.playRandom()
            self.song_path = self.list_path[self.song_index]
            self.song_path = self.song_path.replace('\\', '/')
            self.player.setMedia(QMediaContent(QUrl(self.song_path)))
            self.song_init()
            self.song_start()
            self.song_goBack()

    def song_start(self):
        """播放键，播放切换"""
        # 正在播放
        if self.is_start is True:
            self.player.pause()
            self.is_start = False
            self.timer.stop()
            print('暂停')
            # 注入样式表-暂停（图标为播放）
            self.ui.pushButton_start.setToolTip('播放')
            self.ui.pushButton_start.setStyleSheet("QPushButton{\n"
                                                   "image: url(:/icon/images/暂停.png);\n}\n"
                                                   "QPushButton:hover{\n"
                                                   "image: url(:/icon/images/暂停 深色.png);\n}")
        else:
            # 已选音乐路径
            if self.song_path != '':
                try:
                    self.player.play()
                except Exception as e:
                    print(e)
                self.is_start = True
                print('播放')
                # 注入样式表-播放（图标为暂停）
                self.ui.pushButton_start.setToolTip('暂停')
                self.ui.pushButton_start.setStyleSheet("QPushButton{\n"
                                                       "image: url(:/icon/images/播放中.png);\n}\n"
                                                       "QPushButton:hover{\n"
                                                       "image: url(:/icon/images/播放中 深色.png);\n}")
                self.timer.start(500)

        # 无正在播放，但已导入列表
        if self.song_path == '' and self.file_num != 0:
            self.song_path = self.list_path[self.song_index]
            self.song_path = self.song_path.replace('\\', '/')
            self.player.setMedia(QMediaContent(QUrl(self.song_path)))
            self.song_init()
            self.song_start()
            self.song_goBack()

    def song_init(self):
        """歌曲初始化，导入歌词和时间戳"""
        # 重置索引值，清空列表
        self.lrc_time_index = 0
        self.ui.listWidget_2.clear()
        self.ui.listWidget_comment.clear()
        # 设置评论flag关闭
        self.is_get_comment = False
        # 获取歌曲信息
        self.song_info = readSongInfo(self.song_path, True)
        self.song_info_list = list(self.song_info.values())
        get_lrc = self.song_info_list[5]

        # 在线获取歌词（若启用）
        if self.lrc_mode == 1:
            item_name = self.song_info_list[0] + '-' + self.song_info_list[1]
            music_id = OnlineInfo.getMusicInfo(item_name)['id']
            get_lrc_online = OnlineInfo.getLyric(music_id)
            if get_lrc_online != '':
                get_lrc = get_lrc_online

        # 在线获取评论（若启用）
        if self.comment_mode == 1:
            self.song_getComment()

        self.lrc_dict, self.lrc_time_list = splitLrc(get_lrc)
        # 时间戳不为空，添加歌词
        if len(self.lrc_time_list) != 0:
            for lrc_time in self.lrc_time_list:
                # 翻译模式
                if self.is_lrc_trans is True:
                    if len(self.lrc_dict[lrc_time]) == 1:
                        lrc_output = self.lrc_dict[lrc_time][0]
                    else:
                        lrc_output = self.lrc_dict[lrc_time][0] + '\n' + self.lrc_dict[lrc_time][-1]
                else:
                    lrc_output = self.lrc_dict[lrc_time][0]
                item = QListWidgetItem(lrc_output)
                item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.ui.listWidget_2.addItem(item)
        else:
            item = QListWidgetItem('纯音乐\n/\n歌词无时间戳')
            item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.ui.listWidget_2.addItem(item)

        # 歌曲封面嵌入
        self.ui.label_pic.clear()
        if os.path.exists('cache/cover.png'):
            pix = QPixmap('cache/cover.png')
            self.ui.label_pic.setPixmap(pix)
            self.ui.label_pic.setScaledContents(True)

        # 歌曲信息导入
        self.ui.listWidget_3.clear()
        self.ui.label_name.setText(self.song_info_list[0])
        self.setWindowTitle(self.song_info_list[0] + ' - ' + self.song_info_list[1] + ' - LrcMusicPlayer')
        for info_item in self.song_info:
            if info_item == list(self.song_info.keys())[5]:
                break
            self.ui.listWidget_3.addItem(info_item + ':  ' + self.song_info[info_item])

    def song_getComment(self):
        """导入热门评论"""
        item_name = self.song_info_list[0] + '-' + self.song_info_list[1]
        info = OnlineInfo.getMusicInfo(item_name)
        music_id = info['id']
        music_name = info['name']
        music_artist = info['artist']
        self.ui.listWidget_comment.clear()
        music_com_dict = OnlineInfo.getMusicComment(music_id)
        self.ui.listWidget_comment.addItem(f'评论来自：\nid：{music_id}，\n标题：{music_name}，\n艺术家：{music_artist}\n')
        for item in music_com_dict:
            self.ui.listWidget_comment.addItem(item + '：\n' + music_com_dict[item])
            self.ui.listWidget_comment.addItem('')
        self.is_get_comment = True

    def song_doubleClicked(self):
        """双击歌曲列表"""
        self.is_start = False
        # 获取列表索引值，获取歌曲路径
        self.song_index = self.ui.listWidget.currentRow()
        self.song_path = self.list_path[self.song_index]
        self.song_path = self.song_path.replace('\\', '/')
        self.player.setMedia(QMediaContent(QUrl(self.song_path)))
        self.song_init()
        self.song_start()

    def info_doubleClicked(self):
        """双击歌曲信息"""
        if self.song_info != {}:
            for i in range(5):
                if self.ui.listWidget_3.currentRow() == i:
                    print(self.song_info_list[i])
                    self.ui.lineEdit.setText(self.song_info_list[i])  # 在搜索框中键入文字

    def song_goBack(self):
        """移动到对应位置，选中"""
        # self.ui.listWidget.verticalScrollBar().setSliderPosition(self.song_index)
        self.ui.listWidget.setCurrentRow(self.song_index)
        item = self.ui.listWidget.item(self.song_index)
        self.ui.listWidget.scrollToItem(item, QtWidgets.QAbstractItemView.PositionAtTop)

    def getPath(self):
        """获取文件夹目录"""
        # 清理旧数据
        self.list_path = []
        self.file_num = 0
        self.song_index = 0
        self.ui.listWidget.clear()
        # self.ui.listWidget_2.clear()
        # self.ui.listWidget_3.clear()
        # self.ui.label_pic.clear()
        # self.ui.label_name.clear()
        # 停止播放音乐（先切换为暂停）
        self.is_start = True
        self.song_start()
        self.player.stop()

        # 获取文件夹目录
        self.directory_path = QtWidgets.QFileDialog.getExistingDirectory(self, '选择文件夹', '',
                                                                         options=QtWidgets.QFileDialog.ShowDirsOnly)
        self.getFilePath()

    def getFilePath(self):
        """遍历音乐总数，保存路径及编号"""
        self.check_songs_total()
        if self.file_num == 0:
            mess_str = '无匹配文件'
            print(mess_str)
            QtWidgets.QMessageBox.information(self, "发现歌曲", mess_str, QtWidgets.QMessageBox.Ok)
        else:
            mess_str = '发现' + str(self.file_num) + '首歌，点击Ok导入数据。\n这可能会花费一些时间，请稍候片刻。'
            print(mess_str)
            QtWidgets.QMessageBox.information(self, "发现歌曲", mess_str, QtWidgets.QMessageBox.Ok)

            self.ui.horizontalSlider.setMaximum(self.file_num)
            self.ui.horizontalSlider.setMinimum(0)
            self.thread1.start()  # 开始线程，即建立数据库

    def thread_search_num(self, data):
        """子线程，导入数据的进度反馈"""
        print('已导入第' + str(data) + '个，共' + str(self.file_num) + '个')
        self.ui.horizontalSlider.setValue(data)

    def thread_search_stop(self):
        """子线程，导入数据完成"""
        mess_str = '导入数据完成！共' + str(self.file_num) + '首音乐'
        QtWidgets.QMessageBox.information(self, "导入数据完成", mess_str, QtWidgets.QMessageBox.Ok)
        self.searchTableSelect('')

    def searchSong(self):
        """搜索歌曲"""
        if os.path.exists('songs.db'):
            self.searchTableSelect(self.ui.lineEdit.text())

    def searchTableSelect(self, text):
        """搜索数据库数据"""
        with UsingSqlite(log_time=False, dict_formate=True) as us:
            text = '%{}%'.format(text)
            sql = "select * from music_info where title like ? or artist like ? or album like ? or genre like ? or " \
                  "date like ? or file_name like ?"
            params = (text, text, text, text, text, text)
            result = us.fetch_all(sql, params)

        self.ui.listWidget.clear()
        self.list_path = []
        self.file_num = 0
        for item in result:
            if item['title'] == '暂无':
                item['title'] = item['file_name']
            self.ui.listWidget.addItem(item['title'] + '\n- ' + item['artist'])
            self.list_path.append(item['path'])
            self.file_num += 1

    def check_songs_total(self):
        self.file_num = 0
        for root, dirs, items in os.walk(self.directory_path):
            for item in items:
                file_path = os.path.join(root, item)
                suffix = os.path.splitext(file_path)[-1]
                if suffix != '.flac' and suffix != '.mp3' and suffix != '.wav' and \
                        suffix != '.dsf' and suffix != '.dff':  # 格式限定
                    continue
                self.file_num += 1

    def checkDB(self):
        """检查音乐数目是否一致"""
        self.check_songs_total()

        with UsingSqlite(log_time=False, dict_formate=True) as us:
            sql = "select count(id) as total from music_info"
            result = us.fetch_one(sql)['total']

        if self.file_num == result:
            print('歌曲数目一致')
        elif self.file_num == 0:
            text = '本地：' + str(self.file_num) + '，数据库：' + str(result) + '\n检测到之前的目录歌曲数目为0，请重新选择歌曲路径！'
            print(text)
            QtWidgets.QMessageBox.information(self, "注意！", text, QtWidgets.QMessageBox.Ok)
            self.getPath()
        else:
            text = '本地：' + str(self.file_num) + '，数据库：' + str(result) + '\n检测到歌曲数目不一致，请重新点击左下角按钮导入歌曲数据！'
            print(text)
            QtWidgets.QMessageBox.information(self, "注意！", text, QtWidgets.QMessageBox.Ok)

    def getUpdate(self):
        """获取版本更新"""
        try:
            response = requests.get(
                "https://gitee.com/api/v5/repos/pth2000/LrcMusicPlayer/releases/latest")
        except requests.exceptions.ConnectionError:
            print('获取失败！请检查网络连接')
            str_update = '获取失败！请检查网络连接'
            QtWidgets.QMessageBox.critical(self, "错误", str_update, QtWidgets.QMessageBox.Ok)
        else:
            latest_version = response.json()['tag_name']
            latest_version_name = response.json()['name']
            latest_version_time = response.json()['created_at']
            latest_version_download_url = response.json()['assets'][0]['browser_download_url']
            if not compareVersion(now_version, latest_version):
                str_update = '当前版本为最新版' + '\n服务器版本：' + latest_version + '\n更新时间：' + latest_version_time
                print(str_update)
                QtWidgets.QMessageBox.information(self, "检查更新", str_update, QtWidgets.QMessageBox.Ok)
            else:
                str_update = '发现新版本！' + now_version + ' --> ' + latest_version + '\n更新内容：' + latest_version_name + \
                             '\n更新时间：' + latest_version_time + '\n\n点击 Ok 下载最新版本'
                print(str_update)
                message = QtWidgets.QMessageBox.question(self, "检查更新", str_update, QtWidgets.QMessageBox.Ok
                                                         | QtWidgets.QMessageBox.Cancel)
                if message == QtWidgets.QMessageBox.Ok:
                    webbrowser.open(latest_version_download_url, new=0, autoraise=True)

    def mouseMoveEvent(self, mouse_event):
        """重写函数，实现拖动"""
        if Qt.LeftButton and self.move_drag:
            # 标题栏拖放窗口位置
            self.move(mouse_event.globalPos() - self.move_DragPosition)
            mouse_event.accept()

    def mousePressEvent(self, event):
        """重写鼠标点击的事件"""
        if (event.button() == Qt.LeftButton) and (event.y() < self.ui.widget_top.height()):
            # 鼠标左键点击标题栏区域
            self.move_drag = True
            self.move_DragPosition = event.globalPos() - self.pos()
            event.accept()

    def mouseReleaseEvent(self, mouse_event):
        """鼠标释放后，各扳机复位"""
        self.move_drag = False


class Thread(QtCore.QThread):
    """子线程类"""
    signal_stop = QtCore.pyqtSignal()
    signal_item = QtCore.pyqtSignal(int)

    def __init__(self):
        super().__init__()
        self.stop_flag = 0  # 线程终止信号，主线程通过修改子线程的该属性控制线程终止

    def run(self):
        """重写执行方法"""
        self.creatSQLTable()

    def creatSQLTable(self):
        """建立数据库，建立表单，存储数据"""
        with UsingSqlite(log_time=False, dict_formate=True) as us:
            us.cursor.execute("drop table if exists music_info")
            us.cursor.execute("""create table if not exists music_info (
            id integer primary key autoincrement, 
            file_name text, path text, title text, artist text, album text, date text, genre text
            )""")

            file_num = 0
            for root, dirs, items in os.walk(MyWindow.directory_path):
                for item in items:
                    file_path = os.path.join(root, item)
                    file_name = os.path.splitext(item)[0]
                    suffix = os.path.splitext(file_path)[-1]
                    suffix_limit = ['.flac', '.mp3', '.wav', '.dsf', '.dff']  # 格式限定
                    if suffix not in suffix_limit:
                        continue
                    song_info = readSongInfo(file_path, False)
                    song_info_list = list(song_info.values())
                    sql = "insert into music_info (file_name, path, title, artist, album, date, genre) " \
                          "values (?,?,?,?,?,?,?)"
                    params = (file_name, file_path, song_info_list[0], song_info_list[1], song_info_list[2],
                              song_info_list[3], song_info_list[4])
                    us.cursor.execute(sql, params)
                    file_num += 1
                    self.signal_item.emit(file_num)
        self.signal_stop.emit()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)  # 声明应用程序
    MyWindow = MyWindow()  # 声明窗口
    MyWindow.show()
    sys.exit(app.exec_())  # 当点击窗口的x时，退出程序
